package cn.jofei.netty.ssl;

import cn.jofei.common.config.AppProperties;
import cn.jofei.common.util.Resource;
import lombok.extern.slf4j.Slf4j;

import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManagerFactory;
import java.security.KeyStore;

/**
 * 证书获取
 *
 * @author Jofei Bao
 * @version ngbao v2.0
 * @date 2022年10月22日 12:12
 */
@Slf4j
public class SSLContextFactory {

    private static final String keyPath = AppProperties.get("server.listen.https.key-store-path");

    private static final String password = AppProperties.get("server.listen.https.key-store-password");

    public static KeyManagerFactory getSslContext() {
        try {
            KeyStore kstore = KeyStore.getInstance("PKCS12");
            char[] array = password.toCharArray();
            kstore.load(Resource.loadAsStream(keyPath), array);
            KeyManagerFactory keyFactory = KeyManagerFactory.getInstance("sunx509");
            keyFactory.init(kstore, password.toCharArray());
            return keyFactory;
        } catch (Exception e) {
            log.error("SSL证书加载失败", e);
            return null;
        }
    }
}
